package com.grj.community.all.controller;

import com.grj.community.all.common.RedisKey;
import com.grj.community.all.common.Result;
import com.grj.community.all.entity.Shop;
import com.grj.community.all.service.ShopService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.geo.*;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author 14505
 */
@RestController
@RequestMapping("/shop")
@RequiredArgsConstructor
public class ShopController {
    private final ShopService shopService;
    private final HttpServletResponse httpServletResponse;

    @Resource
    private RedisTemplate redisTemplate;

    @GetMapping("/list/{x}/{y}/{distance}/{limit}")
    public List<Shop>  list(@PathVariable Double x, @PathVariable Double y, @PathVariable Integer distance, @PathVariable Integer limit ){

        GeoResults<RedisGeoCommands.GeoLocation<String>> search = redisTemplate.opsForGeo().search(
                RedisKey.SHOP,
                GeoReference.fromCoordinate(x,y),
                new Distance(distance, Metrics.KILOMETERS),
                RedisGeoCommands.GeoRadiusCommandArgs.newGeoSearchArgs().includeDistance().includeCoordinates().sortAscending().limit(limit)
        );
        assert search != null;
        return search.getContent().stream().map(s -> {
            Shop shop = new Shop();
            String[] split = s.getContent().getName().split("#");
            shop.setId(Long.valueOf(split[0]));
            shop.setName(split[1]);
            shop.setX(s.getContent().getPoint().getX());
            shop.setY(s.getContent().getPoint().getY());
            shop.setDistance(s.getDistance().getValue());
            return shop;
        }).collect(Collectors.toList());
    }

    @GetMapping("/data")
    public Result<Object> data(){
        List<Shop> list = shopService.list();
        redisTemplate.delete(RedisKey.SHOP);
        list.forEach(s->{
            redisTemplate.opsForGeo().add(RedisKey.SHOP, new Point(s.getX(),s.getY()) , s.getId()+"#"+s.getName());
            redisTemplate.opsForGeo().add(RedisKey.SHOP, new Point(s.getX(),s.getY()), s.getId()+"#"+s.getName());
            redisTemplate.opsForGeo().add(RedisKey.SHOP, new Point(s.getX(),s.getY()), s.getId()+"#"+s.getName());
        });
        return Result.success("ok");
    }
}
